#include "iConnection.h"
#include "../util/h/iLogger.h"
#include "../util/h/iMsg.h"
#include "../util/h/iMsgDB.h"
#include "../util/src/iMsgThread.h"
#include "../util/src/iIOThread.h"

iConnection::iConnection(iConnection* prvd, iAllocator* alloc)
:iAllocator::Object(alloc)
,m_provider(prvd)
,m_conn_status(prvd ? iConnection::CS_WAIT_LOCAL_RSP : iConnection::CS_UNSPEC)
{
}
void iConnection::on_connect_confirm()
{
}
void iConnection::on_connect_indication(iClientSocket* cs)
{
}
void iConnection::on_data_indication(iMsgDB* mdb)
{
}
void iConnection::on_write()
{
    if(m_data_q.empty() || m_conn_status==CS_BROKEN)
        return;

    iMsgDB* db = m_data_q.front();
    m_data_q.pop_front();
    DEBUG("data out,len="<<db->get_total_data_length());
    int32_t size = m_socket->send(db);
    if(size == 0)
    {
        m_data_q.push_front(db);
    }
    else if(size != db->get_total_data_length())
    {
        iMsgDB* tail = NULL;
        db->clips(size, tail);
        m_data_q.push_front(tail);
    }
    else
        db->release();
}
void iConnection::on_close()
{
}
int iConnection::on_message(iMsgID msg, void* param)
{
    switch(msg)
    {
    case MSG_TP_DATA_OUT:
        {
            m_data_q.push_back((iMsgDB*)param);
            on_write();       
        }
        break;
    case MSG_TP_CONNECTION_OUT:
        {
			DEBUG("out connecting...");
			if(param)
				m_data_q.push_back((iMsgDB*)param);
            ((iClientSocket*)m_socket)->connect();
            ((iIOThread*)m_worker)->add_io(m_socket);
        }
        break;
    };
	return 0;
}
